
package com.yunhai.xc.conf.shiro;

import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.yunhai.xc.permission.service.PermissionService;
import com.yunhai.xc.role.domain.UserRole;
import com.yunhai.xc.role.service.UserRoleService;
import com.yunhai.xc.user.domain.User;
import com.yunhai.xc.user.service.UserService;
import com.yunhai.xc.util.SubjectUtil;

public class ShiroRealm extends AuthorizingRealm {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	@Lazy
	private UserService userService;
	@Autowired
	@Lazy
	private PermissionService permissionService;

	@Autowired
	@Lazy
	private UserRoleService userRoleService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		User subject = SubjectUtil.getSubject();
		List<UserRole> list = userRoleService.getRoles(subject.getId());
		// 赋予角色
		for (UserRole userRole : list) {
			info.addRole(userRole.getName());
		}
		// 赋予权限
		List<String> permissions = permissionService.getPermissions(subject.getId());
		info.addStringPermissions(permissions);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		String username = token.getUsername();
		logger.info("用户正在登陆,用户名为:{},登录时间为:{}.", username, new Date());
		User user = userService.selectByUserName(username);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),
				ByteSource.Util.bytes(username), this.getName());
		return info;
	}

	/**
	 * 清除缓存
	 */
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}
}
